package com.koron.css2.serviceManage.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.serviceManage.bean.*;
import com.koron.css2.serviceManage.mapper.RoleMapper;
import com.koron.css2.serviceManage.utils.CommonUtils;
import com.koron.util.Constant;
import com.koron.util.JsonUtils;
import com.mysql.cj.util.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bson.types.ObjectId;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.List;

/**
 * 添加角色
 * 
 * @author DaiSn
 * @version 创建时间：2018年10月18日 上午9:09:17
 */
public class RoleAdd implements ServerInterface {

	private static Logger logger = LogManager.getLogger(RoleAdd.class);

	@Override
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
		RoleMapper mapper = factory.getMapper(RoleMapper.class);
		RoleBean bean = null;
		try {
			// 当前水司编号
			String waterGroup = userInfo.getCurWaterCode();
			if (StringUtils.isNullOrEmpty(waterGroup)) {
				return MessageBean.create(Constant.NOT_NULL, "水司编号不能为空", void.class);
			}
			bean = JsonUtils.objectToPojo(req.getData(), RoleBean.class);
			bean.setGroup(waterGroup);
			bean.setCreateBy(userInfo.getUserInfo().getName());
			bean.setCreateTime(CommonUtils.getCurrentTime());
		} catch (Exception e) {
			logger.error("非法参数", e);
			factory.close(false);
			return MessageBean.create(Constant.ILLEGAL_PARAMETER, "非法参数", void.class);
		}
		if(bean!=null){
			// 保存角色信息
			bean.setId(new ObjectId().toHexString());
			mapper.saveRole(bean);
			// 获取当前添加的角色的id
			String roleId = bean.getId();
			// 保存用户-角色信息
			RoleUserBean roleUserBean = new RoleUserBean();
			roleUserBean.setRoleId(roleId);
			if (bean.getOwnNames().size() != 0) {
				roleUserBean.setLoginid(bean.getOwnNames().toString().replace("[", "").replace("]", "").replaceAll(" ", ""));
			}else{
				roleUserBean.setLoginid("");
			}
			mapper.saveRoleUser(roleUserBean);
			//保存角色-模块-操作关系 
			List<RoleModuleBean> rModuleBeans = bean.getrModuleBeans();
			//先删除模块操作信息(以防有历史数据)
			mapper.delRoleModule(roleId);
			if(rModuleBeans.size()!=0){
				//不为空，保存操作模块信息（角色id，为上面添加角色时候，返回的id值）
				for (RoleModuleBean roleModuleBean : rModuleBeans) {
					roleModuleBean.setRoleId(roleId);
					mapper.saveRoleModule(roleModuleBean);
				}
			}
		}
		return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", void.class);
	}

}
